<template>
    <view class="page">
        <view class="content">
            <u-form labelPosition="left"
                    labelWidth="120"
                    :model="form"
                    :rules="rules"
                    ref="uForm">
                <u-form-item prop="s_name" borderBottom>
                    <u-input v-model="s_name" disabledColor="#ffffff" :disabled="true" border="none"/>
                </u-form-item>

                <u-form-item label="手机号" prop="building" borderBottom>
                    <u-input v-model="form.tel" border="none" placeholder="请输入11位手机号"/>
                </u-form-item>
                <u-form-item label="承租人姓名" prop="unit" borderBottom>
                    <u-input v-model="form.r_name" border="none" placeholder="请输入承租人姓名"/>
                </u-form-item>
                <u-form-item label="承租人身份证" prop="room_num" borderBottom>
                    <u-input v-model="form.r_num" border="none" placeholder="请输入有效证件号码"/>
                </u-form-item>
                <u-form-item label="更多(选填)" prop="lock_type" borderBottom @click="toUploadIDCardPage">
                    <u--input v-model="form.lease_priec" disabled disabledColor="#ffffff" border="none" placeholder="上传证件照片"/>
                    <u-icon slot="right" name="arrow-right"></u-icon>
                </u-form-item>

                <u-form-item label="租约起始日" prop="is_elveator" borderBottom @click="openStartTime">
                    <u--input v-model="form.r_time_start" disabled disabledColor="#ffffff" border="none" placeholder="租约起始日"/>
                    <u-icon slot="right" name="arrow-right"></u-icon>
                    <u-datetime-picker :show="startTimeStatus" v-model="startTime" mode="date" @confirm="confirmStartTime" @cancel="cancelStartTime"></u-datetime-picker>
                </u-form-item>

                <u-form-item label="租约截止日" prop="is_elveator" @click="openEndTime">
                    <u--input v-model="form.r_time_end" disabled disabledColor="#ffffff" border="none" placeholder="租约截止日"/>
                    <u-icon slot="right" name="arrow-right"></u-icon>
                    <u-datetime-picker :show="endTimeStatus" :value="endTime" mode="date" @confirm="confirmEndTime" @cancel="cancelEndTime" :key="endTime"></u-datetime-picker>
                </u-form-item>
                <u-row>
                    <view class="u-page__tag-item" v-for="(item, index) in radios" :key="index">
                        <u-tag :text="item.text" :plain="!item.checked" type="primary" :name="index" @click="radioClick"></u-tag>
                    </view>
                </u-row>
                <u-line color="#303133" margin="20rpx 0 0 0"></u-line>
                <u-form-item label="付款方式" prop="payTypeText" borderBottom @click="clickPayType">
                    <u--input v-model="payTypeText" disabled disabledColor="#ffffff" border="none" placeholder="请选择"></u--input>
                    <u-icon slot="right" name="arrow-right"></u-icon>
                    <u-picker :show="showPayType" :columns="payTypeColumns" keyName="label" @confirm="payTypeConfirm" @cancel="cancelPayType"></u-picker>
                </u-form-item>
                <u-form-item label="房屋租金" prop="rent_money" borderBottom>
                    <u-input v-model="form.rent_money" border="none" placeholder="请输入房屋租金金额"/>
                </u-form-item>
                <u-form-item label="房屋押金" prop="cash_money" borderBottom>
                    <u-input v-model="form.cash_money" border="none" placeholder="请输入房屋押金金额"/>
                </u-form-item>

                <u-gap bgColor="#f3f4f6" height="10"></u-gap>
                <u-form-item label="其他费用" prop="lease_priec" borderBottom @click="openOther">
                    <u-input v-model="otherText" disabled disabledColor="#ffffff" border="none"/>
                    <u-tag text="添加费用" slot="right" plain type="warning" icon="plus" @click="openOther"></u-tag>
                    <u-picker :show="otherStatus" ref="otherPicker" :columns="otherColumns" @confirm="confirmOther" @change="otherChangeHandler" @cancel="cancelOther"></u-picker>
                </u-form-item>

                <!--添加费用 - 动态表单-->
                <u-form-item labelWidth="180" :label="item.s_name" borderBottom v-for="(item,index) in otherMoneyList" :key="index">
                    <view style="border-left: 1px solid #303133; padding-left: 20px">
                        <u-input v-model="otherMoneyList[index].money" border="none" placeholder="请输入金额" type="number" clearable/>
                    </view>
                </u-form-item>
                <u-gap bgColor="#f3f4f6" height="10"></u-gap>

                <u-form-item label="收租日" prop="lease_priec" borderBottom @click="openCollect">
                    <u-input v-model="collectText" disabled disabledColor="#ffffff" border="none" placeholder="请选择"/>
                    <u-icon slot="right" name="arrow-right"></u-icon>
                    <u-picker :show="collectStatus" ref="collectPicker" keyName="label" :columns="collectColumns" @confirm="confirmCollect" @change="collectChangeHandler" @cancel="cancelCollect"></u-picker>
                </u-form-item>

                <u-form-item label="更多(选填)" prop="lease_priec" borderBottom @click="toMorePage">
                    <u--input v-model="form.lease_priec" disabled disabledColor="#ffffff" border="none" placeholder="填写备注，合同照片"/>
                    <u-icon slot="right" name="arrow-right"></u-icon>
                </u-form-item>
            </u-form>

            <u-gap height="40"></u-gap>
            <u-row>
                <u-button type="primary" text="确定" @click="finishInput"></u-button>
            </u-row>
        </view>
        <view class="safe-area-inset-bottom"></view>
    </view>
</template>

<script>
    import * as Carbon from "carbonjs";

    export default {
        name: "tenant",
        onLoad(option){
            console.log(option);
            this.s_name = option.s_name;
            this.form.h_id = option.h_id;
            this.form.sh_id = option.z_id;
            this.getOtherMoneyData();
        },
        data(){
            return {
                s_name:'asdasd',
                showPayType: false,
                startTimeStatus: false,
                endTimeStatus: false,
                collectStatus: false,
                otherStatus: false,
                startTime: Number(new Date()),
                endTime: Number(new Date()),
                payTypeText: '',
                collectText: '',
                otherText: '',
                payTypeColumns:[
                    this._everyMonth('押'),this._everyMonth('付'),
                ],
                collectColumns:[
                    [{label: '每期提前', id: 1}, {label: '每期固定', id: 2}],
                    this._everyday('天')
                ],
                collectColumnData: [
                    this._everyday('天'), this._everyday('号')
                ],
                otherColumns:[[],[]],
                otherColumnData: [],
                otherMoneyList: [],
                radios: [
                    {
                        text:'1年',
                        month: 12,
                        checked: false
                    }, {
                        text:'6个月',
                        month: 6,
                        checked: false
                    }, {
                        text:'3个月',
                        month: 3,
                        checked: false
                    }, {
                        text:'1个月',
                        month: 1,
                        checked: false
                    }],
                form:{
                    h_id: '',
                    sh_id: '',
                    tel: '',
                    r_name:'',
                    r_num :'',
                    r_img_z : '',
                    r_img_f : '',
                    r_img_s : '',
                    r_time_start: uni.$u.timeFormat(Number(new Date()), 'yyyy-mm-dd'),
                    r_time_end: uni.$u.timeFormat(Number(new Date()), 'yyyy-mm-dd'),
                    t_time_tag : '',
                    pay_type:'',
                    rent_money:'',
                    cash_money:'',
                    put_time:'',
                    put_type:'',
                },
                rules:{

                }
            };
        },
        methods:{
            getOtherMoneyData(){
                uni.$u.http.get('/api.php/house/get_other_expenses_project',
                    {params:{u_id:uni.getStorageSync('u_id')}}).then(res => {
                    this.otherColumns[1] = res[0].info;

                    for (let i = 0; i < res.length; i++) {
                        this.otherColumns[0].push(res[i].name);
                        this.otherColumnData.push(res[i].info);
                    }
                });
            },
            _everyday(suffix){
                let array = [];
                for (let i = 1; i < 31; i++) {
                    array.push({label:i + suffix, id:i});
                }
                return array;
            },

            _everyMonth(prefix){
                let array = [];
                for (let i = 1; i < 13; i++) {
                    array.push({label: prefix + i, id: i});
                }
                return array;
            },
            payTypeConfirm(e){
                this.form.deposit = this.payTypeColumns[0][e.indexs[0]].id;
                this.form.cope_with = this.payTypeColumns[1][e.indexs[1]].id;
                this.payTypeText = this.payTypeColumns[0][e.indexs[0]].label + '/' +
                    this.payTypeColumns[1][e.indexs[1]].label;

                this.form.pay_type = this.payTypeColumns[0][e.indexs[0]].label +
                    this.payTypeColumns[1][e.indexs[1]].label;
                this.cancelPayType();
            },
            clickPayType(){
                this.showPayType = true;
                uni.hideKeyboard();
            },
            cancelPayType(){
                this.showPayType = false;
            },
            openStartTime(){
                this.startTimeStatus = true;
                uni.hideKeyboard();
            },
            cancelStartTime(){
                this.startTimeStatus = false;
            },
            confirmStartTime(e){
                this.form.r_time_start = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');

                this.cancelStartTime();
            },

            openEndTime(){
                this.endTimeStatus = true;
                uni.hideKeyboard();
            },
            cancelEndTime(){
                this.endTimeStatus = false;
            },
            confirmEndTime(e){
                this.form.r_time_end = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
                this.cancelEndTime();
            },

            openCollect(){
                this.collectStatus = true;
                uni.hideKeyboard();
            },
            cancelCollect(){
                this.collectStatus = false;
            },
            confirmCollect(e){
                this.collectText = e.value[0].label + '/' + e.value[1].label;
                this.form.put_type = e.value[0].id;
                this.form.put_time = e.value[1].id;
                this.cancelCollect();
            },
            collectChangeHandler(e) {
                const {
                    columnIndex,
                    value,
                    values, // values为当前变化列的数组内容
                    index,
                    // 微信小程序无法将picker实例传出来，只能通过ref操作
                    picker = this.$refs.collectPicker
                } = e
                // 当第一列值发生变化时，变化第二列(后一列)对应的选项
                if (columnIndex === 0) {
                    // picker为选择器this实例，变化第二列对应的选项
                    picker.setColumnValues(1, this.collectColumnData[index])
                }
            },

            openOther(){
                this.otherStatus = true;
                uni.hideKeyboard();
            },
            cancelOther(){
                this.otherStatus = false;
            },
            confirmOther(e){
                console.log(e);
                this.otherMoneyList.push({
                    s_name: e.value[1],
                    money: 0
                });
                this.cancelOther();
            },
            otherChangeHandler(e) {
                const {
                    columnIndex,
                    value,
                    values, // values为当前变化列的数组内容
                    index,
                    // 微信小程序无法将picker实例传出来，只能通过ref操作
                    picker = this.$refs.otherPicker
                } = e
                // 当第一列值发生变化时，变化第二列(后一列)对应的选项
                if (columnIndex === 0) {
                    // picker为选择器this实例，变化第二列对应的选项
                    picker.setColumnValues(1, this.otherColumnData[index])
                }
            },
            radioClick(name) {
                this.radios.map((item, index) => {
                    item.checked = index === name;
                });

                // let date = Date.parse(new Date(this.form.r_time_start));//转换为时间戳
                // if (this.radios[name].month === 12) {
                //     date += 86400 * 365 * 1000;//修改后的时间戳
                // }else{
                //     date += (86400 * 30 * 1000) * this.radios[name].month;//修改后的时间戳
                // }
                // this.endTime = date; // 修改卡片的时间

                // this.form.r_time_end = uni.$u.timeFormat(date, 'yyyy-mm-dd'); //修改输入框的时间

                let carbon = Carbon.parse(this.form.r_time_start).add(this.radios[name].month, 'months').add(-1, 'days');
                this.form.r_time_end = carbon.format("YYYY-MM-DD");

                this.endTime = Number(carbon.toDate()); // 修改卡片的时间
                this.form.t_time_tag = this.radios[name].month;
            },

            toUploadIDCardPage(){
                uni.$once('update',(data)=>{
                    this.form.r_img_z = data[0];
                    this.form.r_img_f = data[1];
                    this.form.r_img_s = data[2];
                });
                uni.navigateTo({url:'/pages/landlord/library/upidcard'});
            },
            toMorePage(){
                uni.$once('updateMore',(data)=>{
                    this.form.clause = data.clause;
                    this.form.cost = JSON.stringify(data.cost);
                    this.form.facilities = JSON.stringify(data.facilities);
                    this.form.contract_img = JSON.stringify(data.contract_img);

                });
                uni.navigateTo({url:'/pages/landlord/library/contract'});
            },

            finishInput(){
                let data = uni.$u.deepClone(this.form);
                data.u_id = uni.getStorageSync('u_id');
                data.other_expenses = JSON.stringify(this.otherMoneyList);

                uni.$u.http.post('/api.php/house/user_check', data).then(res => {
                    uni.showToast({
                        title: '添加成功', //提示文字
                        duration: 3000, //显示时长
                        icon: "success", //图标，支持"success"、"loading"
                        success:function () {
                            uni.navigateBack({delta: 1});
                        }
                    });
                });
            }
        }
    }
</script>

<style scoped>
    .page {
        width: 100%;
        min-height: 100vh;
        background-color: #ffffff;
    }

    .content{
        padding: 20rpx;
    }


    .u-page__tag-item {
        margin-left: 30px;
    }
</style>